const router = require('koa-router')()
const send = require('koa-send');
const path = require('path');

router.get('/index.html', async (ctx, next) => {
   var filename = 'index.html';
   await send(ctx,filename,{root: path.resolve(__dirname,'../views')});
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get("/test204",async(ctx,next)=>{
	console.log("204请求");
})

router.get("/test301",async(ctx,next)=>{
	ctx.status = 301;
	ctx.redirect('/cart');
	ctx.body = '永久重定向到其他地方去了';
})

router.get("/test302",async(ctx,next)=>{
	ctx.redirect('/login');
})

router.get("/test401",async(ctx,next)=>{
	var token = ctx.request.header.authorization;
	if(token == "123abc"){
		ctx.body = "认证成功"
	}else{
		ctx.status = 401;
		ctx.body = '认证失败';
	}
})
router.get("/test403/1.png",async(ctx,next)=>{
	ctx.status = 403;
	ctx.body = "该资源禁止访问";
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: '极火网',
    website: "www.githuo.com",
    author: "朱蒙托"
  }
})

router.get('/userInfo', async (ctx, next) => {
	var info = ctx.query;
	var username = info.username;
	var arr = [
		{username: "githuo",age: "33"},
		{username: "zmt",age:"33"},
		{username: "朱蒙托",age:30}
	]
	var rs = arr.filter(function(item){
		if(item.username == username){
			return true;
		}else{
			return false;
		}
	})
	if(rs.length>0){
		ctx.body = rs;
	}else{
		ctx.body = {
			message: "您查询的信息不存在"
		}
	}
  
})

router.post("/login",async (ctx,next)=>{
	console.log("post请求");
	 var body = ctx.request.body;
	 console.log(ctx.request.body);
	 var users = [
	 	{username:"zmt",password: 123},
	 	{username:"zjt",password: 456},
	 	{username:"githuo",password: 789}
	 ]
	 var isSuccess = false;
	 users.filter(function(item){
	 	if(item.username == body.username && item.password == body.password){
	 		isSuccess = true;
	 		return true;
	 	}else{
	 		return false;
	 	}
	 })
	 ctx.body = isSuccess?{message: "登录成功",username: body.username}: {message: "登录失败,用户名或密码错误,请重新登录"}
})

module.exports = router
